<?php
require_once 'config.inc.php';

//
//Functions:
//

//Setup logging
function log_message ($message, $die = TRUE) {
  $message = date('Y-m-d H:i:s T') . ' - ' . $message . "\n";
  file_put_contents(dirname(__FILE__) . '/errors.txt', $message, FILE_APPEND);
  if ($die) {
    die;
  }
}

//Connect to forums database
function connect_forums_db () {
  global $config;
  mysql_connect($config['Forums DB']['Server'] . ':' . $config['Forums DB']['Port'], $config['Forums DB']['Username'], $config['Forums DB']['Password']) or log_message('Error connecting to forums database server.');
  mysql_select_db($config['Forums DB']['Database']) or log_message('Error selecting forums database.');
}

//Connect to TS server
function connect_ts ($nickname_suffix = '') {
  require_once 'TeamSpeak3/TeamSpeak3.php';
  global $config;
  if (!empty($nickname_suffix)) {
    $config['TS Server']['Script Nickname'] .= $nickname_suffix;
  }
  $config['TS Server']['Script Nickname'] = rawurlencode($config['TS Server']['Script Nickname']);
  try {
    return TeamSpeak3::factory(<<<EOL
serverquery://{$config['TS Server']['SQ Username']}:{$config['TS Server']['SQ Password']}@{$config['TS Server']['Server']}:{$config['TS Server']['SQ Port']}/?server_port={$config['TS Server']['Port']}&nickname={$config['TS Server']['Script Nickname']}
EOL
    );
  }
  catch (Exception $exception) {
    return FALSE;
  }
}

//Get client's TS DB ID
function get_ts_user_db_id ($server, $uid) {
  try {
    return $server->clientFindDb($uid, TRUE);
  }
  catch (Exception $exception) {
    if (strpos($exception, 'database empty result set') !== FALSE) {
      return FALSE;
    }
    log_message('An unknown exception happened while getting TS client database ID based on Unique ID. UID: ' . $uid, FALSE);
    return 1;
  }
}

//Get EVE Corporation ID, return FALSE on key error or -1 on connection error
function get_eve_corp ($key_id, $ver_code, $char_name) {
  if (!($characters = simplexml_load_file('https://api.eveonline.com/account/APIKeyInfo.xml.aspx?keyID=' . $key_id . '&Vcode=' . $ver_code))) {
    return -1;
  }

  if (isset($characters->error) and substr((string) $characters->error->attributes()->code, 0, 1) == 2) {
    log_message('API Key authentication failed. User: ' . $char_name, FALSE);
    return FALSE;
  }
  elseif (!isset($characters->result->key->rowset->row)) {
    log_message('Error getting EVE character list, but there was no API authentication failure message.  Quitting. User: ' . $char_name);
  }
  
  global $config;

  if (((int) $characters->result->key->attributes()->accessMask & $config['Minimum Access Mask']) != $config['Minimum Access Mask']) {
    log_message('Error: Key has invalid access mask. User: ' . $char_name, FALSE);
    return FALSE;
  }

  if ($config['Account Key Required'] and (string) $characters->result->key->attributes()->type != 'Account') {
    log_message('Error: Key should be an account-level key but isn\'t. User: ' . $char_name, FALSE);
    return FALSE;
  }

  foreach($characters->result->key->rowset->row as $row) {
    if ($row->attributes()->characterName == $char_name) {
      return array((string) $row->attributes()->corporationID, strtotime((string) $characters->cachedUntil . ' UTC'));
    }
  }
  log_message('Error finding character in character list. User: ' . $char_name, FALSE);
  return FALSE;
}

//Check if user is logged in on the forums and get their user id
function get_forums_user_id () {
  global $config;
  $query = <<<EOL
SELECT config_name, config_value
FROM {$config['Forums DB']['Table Prefix']}config
WHERE config_name IN ('cookie_name', 'session_length')
EOL;
  $result = mysql_query($query) or die('Error getting phpBB cookie information.');
  while ($row = mysql_fetch_assoc($result)) {
    $forums_config[$row['config_name']] = $row['config_value'];
  }
  if (empty($forums_config['cookie_name']) or empty($forums_config['session_length'])) {
    die('Error getting some needed forums configuration information.');
  }
  if (!isset($_COOKIE[$forums_config['cookie_name'] . '_u'])) {
    die('Error: You are not logged in on the forums.  Please do so and then try to register again.');
  }
  
  $cookie['User ID'] = mysql_real_escape_string($_COOKIE[$forums_config['cookie_name'] . '_u']);
  $cookie['Session ID'] = mysql_real_escape_string($_COOKIE[$forums_config['cookie_name'] . '_sid']);
  $query = <<<EOL
SELECT session_user_id AS `User ID`
FROM {$config['Forums DB']['Table Prefix']}sessions
WHERE session_user_id = "{$cookie['User ID']}"
AND session_id = "{$cookie['Session ID']}"
AND UNIX_TIMESTAMP() - session_time < "{$forums_config['session_length']}"
EOL;
  $result = mysql_query($query) or die('Error checking if you are logged in on the forums.');
  $session = mysql_fetch_assoc($result) or die('Error: Your forums session has expired.  Please log in the forums and then try to register again.');
  if ($session['User ID'] == 1) {
    die('Error: You are not logged in on the forums.  Please do so and then try to register again.');
  }
  return $session['User ID'];
}
?>